﻿using System.Reflection;
using Foundation.Entity;

namespace Dyao.Book.Core
{
    /// <summary>
    /// 实体扩展
    /// </summary>
    public static class EntityExtensions
    {
        /// <summary>
        /// 使用 changed 值，更新实体 entity
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <param name="changed"></param>
        public static void UpdateEntity<TEntity>(this TEntity entity,TEntity changed) 
            where TEntity : class,IEntity
        {
            if (entity == null) return;
            if (changed == null) entity = null;

            var properties = typeof(TEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty);
            foreach (var property in properties)
            {
                var pValue = property.GetValue(changed);
                property.SetValue(entity, pValue);
            }
        }

        /// <summary>
        ///  使用 changed 值，更新实体 entity
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="changeds"></param>
        public static void UpdateEntity<TEntity>(this IEnumerable<KeyValuePair<TEntity,TEntity>> changeds)
            where TEntity : class, IEntity
        {
            foreach(var item in changeds)
            {
                UpdateEntity(item.Key, item.Value);
            }
        }
    }
}
